package com.lu.pojo.network.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author luzhenfang
 * @date 2020 05 16
 * @description tcp 服务端
 */
public class TcpServer {
    private ServerSocket serverSocket = null;
    private Socket socket = null;
    private InputStream is = null;
    private ByteArrayOutputStream baos =null;

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(9999);
    }
    public TcpServer(int port) throws IOException {
        // 等待链接
        try {
            serverSocket = new ServerSocket(port);
            socket = this.serverSocket.accept();
            is = socket.getInputStream();
            // 管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (baos!=null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
